// 包裹跟踪管理类
class PackageTracker {
    constructor() {
        this.currentPackage = null;
        this.matchedBatch = null;
        this.currentBatch = null;
        this.batches = [];
        this.scanPackages = [];
        this.batchPackages = [];
        this.reportPackages = [];
        this.selectedScanPackages = [];
        this.selectedBatchPackages = [];
        this.selectedReportPackages = [];
        this.selectAllScan = false;
        this.selectAllBatch = false;
        this.selectAllReport = false;
        this.batchStats = {
            total: 0,
            scanned: 0,
            unscanned: 0,
            completion: 0
        };
        this.reportStats = {
            total: 0,
            scanned: 0,
            unscanned: 0,
            completion: 0
        };
        this.reportFilters = {
            batch_id: '全部',
            status: '全部'
        };

        this.initialize();
    }

    // 初始化
    initialize() {
        this.loadBatches();
        this.setupEventListeners();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 批次选择变更
        document.getElementById('batch-select')?.addEventListener('change', (e) => {
            this.changeBatch(e.target.value);
        });

        // 扫描输入处理
        document.getElementById('scan-input')?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.processScan();
            }
        });
    }

    // 加载批次列表
    async loadBatches() {
        try {
            const response = await fetch('/api/batches');
            const data = await response.json();
            this.batches = data;
        } catch (error) {
            console.error('Error loading batches:', error);
            window.notificationManager.showMessage('加载批次列表失败', 'error');
        }
    }

    // 切换批次
    changeBatch(batchId) {
        if (this.currentBatch) {
            window.wsManager.leaveBatch(this.currentBatch);
        }
        this.currentBatch = batchId;
        if (batchId) {
            window.wsManager.joinBatch(batchId);
            document.getElementById('scan-input')?.focus();
        }
    }

    // 处理扫描
    processScan() {
        const scanInput = document.getElementById('scan-input');
        if (!scanInput) return;

        const packageId = scanInput.value.trim();
        if (!this.currentBatch) {
            window.notificationManager.showMessage('请先选择批次', 'error');
            return;
        }
        
        if (packageId) {
            window.wsManager.sendScanRequest(packageId, this.currentBatch);
            scanInput.value = '';
        }
    }

    // 更新批次统计
    updateBatchStats(stats) {
        this.batchStats = stats;
    }

    // 处理文件导入
    handleFileImport(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const content = e.target.result;
                this.processImportedData(content, 'file');
            };
            reader.readAsText(file);
        }
    }

    // 处理导入数据
    processImportedData(content, type) {
        const packages = content.split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0);

        if (packages.length === 0) {
            window.notificationManager.showMessage('没有找到有效的包裹数据', 'error');
            return;
        }

        // 发送到服务器进行处理
        this.importPackages(packages, type);
    }

    // 导入包裹
    async importPackages(packages, type) {
        try {
            const response = await fetch('/api/packages/import', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    packages,
                    type,
                    batch_id: this.currentBatch
                })
            });

            const data = await response.json();
            if (data.success) {
                window.notificationManager.showMessage('包裹导入成功', 'success');
                this.loadBatchPackages(this.currentBatch);
            } else {
                window.notificationManager.showMessage(data.error || '包裹导入失败', 'error');
            }
        } catch (error) {
            console.error('Error importing packages:', error);
            window.notificationManager.showMessage('包裹导入失败', 'error');
        }
    }

    // 加载批次包裹
    async loadBatchPackages(batchId) {
        try {
            const response = await fetch(`/api/batches/${batchId}/packages`);
            const data = await response.json();
            this.batchPackages = data;
        } catch (error) {
            console.error('Error loading batch packages:', error);
            window.notificationManager.showMessage('加载批次包裹失败', 'error');
        }
    }

    // 生成报表
    async generateReport() {
        try {
            const response = await fetch('/api/reports/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(this.reportFilters)
            });

            const data = await response.json();
            this.reportPackages = data.packages;
            this.reportStats = data.stats;
        } catch (error) {
            console.error('Error generating report:', error);
            window.notificationManager.showMessage('生成报表失败', 'error');
        }
    }

    // 导出报表
    async exportReport() {
        try {
            const response = await fetch('/api/reports/export', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(this.reportFilters)
            });

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'report.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('Error exporting report:', error);
            window.notificationManager.showMessage('导出报表失败', 'error');
        }
    }

    // 切换全选包裹
    toggleAllPackages(type) {
        switch (type) {
            case 'scan':
                this.selectAllScan = !this.selectAllScan;
                this.selectedScanPackages = this.selectAllScan ? 
                    this.scanPackages.map(pkg => pkg.package_id) : [];
                break;
            case 'batch':
                this.selectAllBatch = !this.selectAllBatch;
                this.selectedBatchPackages = this.selectAllBatch ? 
                    this.batchPackages.map(pkg => pkg.package_id) : [];
                break;
            case 'report':
                this.selectAllReport = !this.selectAllReport;
                this.selectedReportPackages = this.selectAllReport ? 
                    this.reportPackages.map(pkg => pkg.package_id) : [];
                break;
        }
    }

    // 删除选中的包裹
    async deleteSelectedPackages(type) {
        let selectedPackages;
        switch (type) {
            case 'scan':
                selectedPackages = this.selectedScanPackages;
                break;
            case 'batch':
                selectedPackages = this.selectedBatchPackages;
                break;
            case 'report':
                selectedPackages = this.selectedReportPackages;
                break;
            default:
                return;
        }

        if (selectedPackages.length === 0) {
            window.notificationManager.showMessage('请先选择要删除的包裹', 'error');
            return;
        }

        try {
            const response = await fetch('/api/packages/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    package_ids: selectedPackages
                })
            });

            const data = await response.json();
            if (data.success) {
                window.notificationManager.showMessage('包裹删除成功', 'success');
                // 重新加载相应的数据
                switch (type) {
                    case 'scan':
                        this.loadBatchPackages(this.currentBatch);
                        break;
                    case 'batch':
                        this.loadBatchPackages(this.currentBatch);
                        break;
                    case 'report':
                        this.generateReport();
                        break;
                }
            } else {
                window.notificationManager.showMessage(data.error || '包裹删除失败', 'error');
            }
        } catch (error) {
            console.error('Error deleting packages:', error);
            window.notificationManager.showMessage('包裹删除失败', 'error');
        }
    }
}

// 创建全局包裹跟踪管理器实例
window.packageTracker = new PackageTracker(); 